﻿using System.Diagnostics.CodeAnalysis;

namespace System;

/// <summary>
/// 这个类可用于在调用 Dispose 方法时提供一个操作
/// </summary>
public class DisposeAction : IDisposable
{
    private readonly Action _action;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="action">当这个对象被释放时要执行的操作</param>
    public DisposeAction([NotNull] Action action)
    {
        ArgumentNullException.ThrowIfNull(action);

        _action = action;
    }

    public void Dispose()
    {
        _action();
    }
}

/// <summary>
/// 这个类可用于在调用 Dispose 方法时提供一个操作
/// <typeparam name="T">操作的参数类型</typeparam>
/// </summary>
public class DisposeAction<T> : IDisposable
{
    private readonly Action<T> _action;

    private readonly T? _parameter;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="action">当这个对象被释放时要执行的操作</param>
    /// <param name="parameter">操作的参数</param>
    public DisposeAction(Action<T> action, T parameter)
    {
        ArgumentNullException.ThrowIfNull(action);

        _action = action;
        _parameter = parameter;
    }

    public void Dispose()
    {
        if (_parameter != null)
        {
            _action(_parameter);
        }
    }
}
